import axios from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router'

// 允许通过环境变量覆盖 API 基址
const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'

const instance = axios.create({
  baseURL,
  timeout: 100000
})

instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.token = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 1) {
      return res
    }
    return Promise.reject(res.data)
  },
  (err) => {
    ElMessage({
      message: err.response.data.message || '服务异常',
      type: 'error'
    })
    console.log(err)
    if (err.response?.status === 401) {
      router.push('/login')
      const userStore = useUserStore()
      userStore.clearUserInfo()
      ElMessage({ message: '身份验证失败,请重新登录', type: 'error' })
    }
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
